'use strict';

const Service = require('egg').Service;

class AccountsService extends Service {
  async index(query) {
    query = query || {};
    const params = { attributes: { exclude: [ 'password' ] } }; // 排除password字段
    const sort = query.sortOrder ? query.sortOrder.toUpperCase() : 'DESC';
    const Op = this.app.Sequelize.Op;

    params.order = [[ 'id', sort ]]; params.raw = true;
    params.offset = query.offset ? parseInt(query.offset) : 0;
    params.limit = query.limit ? parseInt(query.limit) : 999;
    params.sortOrder = query.sortOrder || 'desc';
    params.where = {};

    delete query.offset;
    delete query.limit;
    delete query.sortOrder;
    delete query.page;

    for (const key in query) {
      params.where[key] = {
        [Op.like]: `%${query[key]}%`,
      };
    }
    params.include = [{
      model: this.ctx.model.Role,
      attributes: [[ 'title', 'roleName' ]],
    }];

    try {
      return await this.ctx.model.User.findAndCountAll(params);
    } catch (e) {
      return e.message;
    }
  }

  async new(data) {
    const { ctx } = this;
    // 校验data是否有必需字段
    try {
      const result = await ctx.model.User.create({
        account: data.account,
        role_id: data.role_id,
        password: ctx.helper.md5(data.password),
        name: data.name,
        email: data.email,
        status: data.status === '1' ? 1 : 0,
      });
      return result;
    } catch (e) {
      return e.message;
    }
  }

  async edit(id, data) {
    const { ctx } = this;
    const field = {};
    for (const key in data) {
      if (data[key]) {
        if (key === 'password') field[key] = ctx.helper.md5(data[key]);
        else if (key !== 'id') field[key] = data[key];
      }
    }
    try {
      const result = await ctx.model.User.update(field, { where: { id } });
      return result;
    } catch (e) {
      return e.message;
    }
  }

  async show(id) {
    const { ctx } = this;
    try {
      const result = await ctx.model.User.findOne({ attributes: { exclude: [ 'password' ] }, where: { id }, raw: true });
      return result;
    } catch (e) {
      return e.message;
    }
  }

  async destroy(id) {
    const { ctx } = this;
    try {
      const result = await ctx.model.User.destroy({ where: { id } });
      return result;
    } catch (e) {
      return e.message;
    }
  }

  //  const user = await this.ctx.db.query('select * from user where uid = ?', uid);
  //  return user;
}

module.exports = AccountsService;
